<template>
    <div class="devices">
        <el-card>
            <template #header>
                <div class="card-header">
                    <h3>设备管理</h3>
                    <el-button type="primary" @click="handleAdd">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加设备
                    </el-button>
                </div>
            </template>

            <el-table :data="devices" style="width: 100%">
                <el-table-column prop="name" label="设备名称" />
                <el-table-column prop="type" label="类型" />
                <el-table-column prop="location" label="位置" />
                <el-table-column prop="status" label="状态">
                    <template #default="{ row }">
                        <el-switch v-model="row.status" @change="(value: boolean) => handleStatusChange(row, value)"
                            active-text="在线" inactive-text="离线" :loading="row.statusLoading" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                        <el-button-group>
                            <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加/编辑设备对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加设备' : '编辑设备'" width="500px">
            <el-form :model="deviceForm" :rules="rules" ref="deviceFormRef" label-width="80px">
                <el-form-item label="设备名称" prop="name">
                    <el-input v-model="deviceForm.name" />
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="deviceForm.type" placeholder="请选择设备类型">
                        <el-option label="照明" value="照明" />
                        <el-option label="空调" value="空调" />
                        <el-option label="厨具" value="厨具" />
                        <el-option label="其他" value="其他" />
                    </el-select>
                </el-form-item>
                <el-form-item label="位置" prop="location">
                    <el-input v-model="deviceForm.location" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deviceService } from '@/api/services'

interface Device {
    id: number
    name: string
    type: string
    location: string
    status: boolean
    statusLoading: boolean
}

const devices = ref<Device[]>([])

const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const deviceFormRef = ref<FormInstance>()

const deviceForm = reactive({
    id: 0,
    name: '',
    type: '',
    location: ''
})

const rules = {
    name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
    location: [{ required: true, message: '请输入设备位置', trigger: 'blur' }]
}

const resetForm = () => {
    deviceForm.id = 0
    deviceForm.name = ''
    deviceForm.type = ''
    deviceForm.location = ''
}

const handleAdd = () => {
    dialogType.value = 'add'
    resetForm()
    dialogVisible.value = true
}

const handleEdit = (row: Device) => {
    dialogType.value = 'edit'
    Object.assign(deviceForm, row)
    dialogVisible.value = true
}

const handleDelete = async (row: Device) => {
    try {
        await ElMessageBox.confirm('确定要删除该设备吗？', '提示', {
            type: 'warning'
        })
        await deviceService.deleteDevice(row.id)
        devices.value = devices.value.filter(item => item.id !== row.id)
        ElMessage.success('删除成功')
    } catch (error: any) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '删除失败，请重试')
        }
    }
}

const handleSubmit = async () => {
    if (!deviceFormRef.value) return

    try {
        await deviceFormRef.value.validate(async (valid) => {
            if (valid) {
                if (dialogType.value === 'add') {
                    // 调用添加API
                    const newDevice = {
                        name: deviceForm.name,
                        type: deviceForm.type,
                        location: deviceForm.location,
                        status: true
                    }
                    const response = await deviceService.addDevice(newDevice)
                    devices.value.push({
                        ...response.data,
                        statusLoading: false
                    })
                } else {
                    // 调用更新API
                    const updateData = {
                        name: deviceForm.name,
                        type: deviceForm.type,
                        location: deviceForm.location
                    }
                    await deviceService.updateDevice(deviceForm.id, updateData)
                    const index = devices.value.findIndex(item => item.id === deviceForm.id)
                    if (index !== -1) {
                        devices.value[index] = {
                            ...devices.value[index],
                            ...updateData,
                            statusLoading: false
                        }
                    }
                }

                dialogVisible.value = false
                ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
            }
        })
    } catch (error: any) {
        ElMessage.error(error.message || '操作失败，请重试')
    }
}

const handleStatusChange = async (device: Device, val: boolean): Promise<void> => {
    try {
        device.statusLoading = true
        await deviceService.toggleDevice(device.id, val)
        device.status = val // 更新本地状态
        ElMessage.success(`设备${val ? '已启动' : '已关闭'}`)
    } catch (error) {
        device.status = !val // 恢复状态
        ElMessage.error('操作失败，请重试')
    } finally {
        device.statusLoading = false
    }
}

const loadDevices = async () => {
    try {
        const response = await deviceService.getAllDevices()
        devices.value = response.data.map(device => ({
            ...device,
            statusLoading: false
        }))
    } catch (error: any) {
        ElMessage.error(error.message || '加载设备列表失败')
    }
}

onMounted(() => {
    loadDevices()
})
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h3 {
    margin: 0;
    font-size: 18px;
    color: #303133;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>